package com.inspur.dgov.vlbod.controller;


import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.inspur.dgov.vlbod.constant.ServiceConstant;
import com.inspur.dgov.vlbod.entity.LiveBroadcast;
import com.inspur.dgov.vlbod.entity.LiveVideoPullurls;
import com.inspur.dgov.vlbod.http.DgovResponse;
import com.inspur.dgov.vlbod.secure.token.UserRecord;
import com.inspur.dgov.vlbod.service.LiveBroadcastService;
import com.inspur.dgov.vlbod.service.LiveVideoPullurlsService;
import com.inspur.dgov.vlbod.service.UserRecordService;
import com.inspur.dgov.vlbod.util.CTools;
import com.inspur.dgov.vlbod.vo.LiveBroadcastVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

/**
 * 直播服务控制器
 *
 * @Author chiyupei
 * @Date 2023/5/28 18:42
 * @Version 1.0
 * @Description 直播服务控制器
 */
@Slf4j
@RestController
@RequestMapping("/live")
public class LiveBroadcastController {

    /**
     * 小鱼视频配置-直播分辨率
     */
    @Value("${dgov.xyvideo.defaultResolution:'DEFAULT'}")
    private String defaultResolution;

    @Autowired
    private UserRecordService userRecordService;

    @Autowired
    private LiveBroadcastService liveBroadcastService;
    @Autowired
    LiveVideoPullurlsService liveVideoPullurlsService;

    /**
     * 直播列表查询
     *
     * @param data：直播列表查询参数（type：类型（1-我的直播，2-我的收藏，3-直播列表），pageNo：页码，pageSize：每页条数，searchContext：查询关键字）
     * @return DgovResponse
     */
    @PostMapping("/list")
    public DgovResponse list(HttpServletRequest request, @RequestBody JSONObject data) {
        try {
            // 直播列表类型校验
            String type = data.getString("type");
            if (!StrUtil.equalsAny(type, "1", "2", "3")) {
                return DgovResponse.fail("请检查直播列表类型");
            }
            // 获取当前登录用户ID
            String userId = userRecordService.getUserRecord(request).getUserId();
            data.put("userId", userId);
            // 获取分页条件
            int pageNo = data.getIntValue("pageNo");
            if (0 == pageNo) {
                pageNo = 1;
            }
            int pageSize = data.getIntValue("pageSize");
            if (0 == pageSize) {
                pageSize = 10;
            }

            Page<LiveBroadcastVO> page = new Page<>(pageNo, pageSize);
            Page<LiveBroadcastVO> pageList;
            // 我的直播
            if ("1".equals(type)) {
                pageList = this.liveBroadcastService.queryMyList(page, data);
            } else if ("2".equals(type)) {
                // 我的收藏
                pageList = this.liveBroadcastService.queryCollectList(page, data);
            } else {
                // 直播列表
                pageList = this.liveBroadcastService.queryList(page, data);
            }
            return DgovResponse.success(pageList);
        } catch (Exception e) {
            log.error("/live/list error:" + e.getMessage());
            return DgovResponse.fail("直播列表查询失败");
        }
    }

    /**
     * 获取直播详情信息
     *
     * @param id 直播ID
     * @return
     */
    @GetMapping("/info/{id}")
    public DgovResponse info(@PathVariable String id) {
        LiveBroadcast bean = this.liveBroadcastService.getById(id);
        return DgovResponse.success(bean);
    }

    /**
     * 获取直播详情信息
     *
     * @param id 直播ID
     * @return
     */
    @GetMapping("/videourls/{id}")
    public DgovResponse getVideourls(@PathVariable String id) {
        List<LiveVideoPullurls> liveVideoPullurls =
                this.liveBroadcastService.getLiveBroadcastVideoPullList(id);
        return DgovResponse.success(liveVideoPullurls);
    }

    /**
     * 保存直播信息
     *
     * @param request
     * @param data 直播信息
     * @return
     */
    @PostMapping("/save")
    public DgovResponse save(HttpServletRequest request, @RequestBody LiveBroadcast data) {
        try {
            // 获取当前登录用户ID
            UserRecord userRecord = this.userRecordService.getUserRecord(request);
            String userId = userRecord.getUserId();
            if (StrUtil.isEmpty(data.getId())) {
                // 直播新建保存
                String id = CTools.getSnowflakeId();
                data.setId(id);
                // 根据开始时间和时长计算结束时间
                data.setEndTime(data.getStartTime().plusMinutes(data.getDurationTime()));
                // 是否自动录制
                String autoRecord = data.getAutoRecording();
                if (StrUtil.isNotEmpty(autoRecord) && ServiceConstant.SYSTEM_ON.equals(autoRecord)) {
                    data.setAutoPublishRecording(ServiceConstant.SYSTEM_ON);
                } else {
                    data.setAutoRecording(ServiceConstant.SYSTEM_OFF);
                    data.setAutoPublishRecording(ServiceConstant.SYSTEM_OFF);
                }
                // 直播分辨率
                data.setDefaultResolution(defaultResolution);
                data.setStatus(ServiceConstant.SYSTEM_ON);
                data.setUserId(userId);
                data.setUserName(userRecord.getUserName());
                data.setOrganCode(userRecord.getOrganCode());
                data.setCreateTime(LocalDateTime.now());
                data.setLiveState(ServiceConstant.LIVE_NOSTART);
                // TODO 补充直播附加配置
                this.liveBroadcastService.saveLiveBroadcast(data);
            } else {
                // 直播修改保存
                LiveBroadcast liveBroadcast = this.liveBroadcastService.getById(data.getId());
                data.setLiveId(liveBroadcast.getLiveId());
                data.setMeetingRoomNumber(liveBroadcast.getMeetingRoomNumber());
                data.setControlPassword(liveBroadcast.getControlPassword());
                // 根据开始时间和时长计算结束时间
                data.setEndTime(data.getStartTime().plusMinutes(data.getDurationTime()));
                // 是否自动录制
                String autoRecord = data.getAutoRecording();
                if (StrUtil.isNotEmpty(autoRecord) && ServiceConstant.SYSTEM_ON.equals(autoRecord)) {
                    data.setAutoPublishRecording(ServiceConstant.SYSTEM_ON);
                } else {
                    data.setAutoRecording(ServiceConstant.SYSTEM_OFF);
                    data.setAutoPublishRecording(ServiceConstant.SYSTEM_OFF);
                }
                this.liveBroadcastService.updateLiveBroadcast(data);
            }
            return DgovResponse.success();
        } catch (Exception e) {
            log.error("/live/save error:" + e.getMessage());
            return DgovResponse.fail("直播信息保存失败");
        }
    }

    /**
     * 删除直播信息
     *
     * @param id
     * @return
     */
    @GetMapping("/delete/{id}")
    public DgovResponse delete(@PathVariable String id) {
        // 删除小鱼直播信息，删除小鱼会议信息，删除直播视频信息，删除直播收藏信息，删除直播点赞信息，删除直播信息
        LiveBroadcast broadcast = this.liveBroadcastService.getById(id);
        this.liveBroadcastService.deleteLiveBroadcast(broadcast);
        return DgovResponse.success();
    }

    /**
     * 根据直播id获取拉流地址
     * @param id
     * @return
     */
    @GetMapping("/getPulls/{id}")
    public DgovResponse getPulls(@PathVariable String id) {
        LambdaQueryWrapper<LiveVideoPullurls> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(LiveVideoPullurls::getBroadcastId,id);
        List<LiveVideoPullurls> list = this.liveVideoPullurlsService.list(queryWrapper);
        return DgovResponse.success(list);
    }

    /**
     * 开始直播
     * @param request request
     * @param id 直播id
     * @param deplay 推流延迟
     * @return 结果
     */
    @GetMapping(value = "/start/{id}")
    public DgovResponse startLiveBroadcast(HttpServletRequest request,@PathVariable("id") String id,
                                           @RequestParam(value = "deplay",required = false,defaultValue = "15") Integer deplay){
        try {
            UserRecord userRecord = this.userRecordService.getUserRecord(request);
            Map<String, Object> objectMap = liveBroadcastService.startLiveBroadcast(id, deplay, userRecord);
            log.info("output start live return info {}",JSONUtil.toJsonStr(objectMap));
            JSONObject result = new JSONObject();
            result.put("token", objectMap.get("token"));
            result.put("param", objectMap);
            return DgovResponse.success(result);
        }catch (Exception exception){
            return DgovResponse.fail(exception);
        }
    }

}
